import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIp , int serverPort)throws IOException {
        //需要创建Socket的同时，和服务器建立连接，此时就得告诉Socket服务器在哪
        //具体建立连接的细节，不需要代码实现，内核处理完成
        //当我们new这个对象的时候，操作系统内核，就开始三次握手具体的细节，完成建立连接的过程了
        socket = new Socket(serverIp,serverPort);
    }
    public void start(){
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream()){
            PrintWriter writer = new PrintWriter(outputStream);
            Scanner scannerNetwork = new Scanner(inputStream);
            while(true){
                //1.从控制台读取数据
                System.out.printf("->");
                String request = scanner.next();
                //2.把字符串作为请求，发送给服务器
                writer.println(request);
                //这里使用println是为了和服务器的scanner.next对应起来
                writer.flush();
                //3.读取服务器返回的响应
                String response = scannerNetwork.next();
                //4.在界面上显示内容
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
